package com.servicesystem.servicesystem.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.servicesystem.servicesystem.entity.douyin.vo.oauth.OauthVO;
import com.servicesystem.servicesystem.service.OauthService;
import com.servicesystem.servicesystem.untis.Http;
import com.servicesystem.servicesystem.untis.HttpRequestAll;
import com.servicesystem.servicesystem.untis.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author X
 * @version 1.0
 * @ClassName OauthServiceImpl
 * @description
 * @date 2020/9/8
 **/
@Service
public class OauthServiceImpl implements OauthService {

    private static final String app_key = "6845190554020480520";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /***
     * 自用型授权获取access_token
     * @return
     */
    @Override
    public OauthVO getAccessToken() throws Exception {

        String appKey = "6845190554020480520";
        String appSecret = "8963b551-bd04-4be5-b02b-2e82ee0fccdb";
        String url = "https://openapi-fxg.jinritemai.com/oauth2/access_token?app_id=" + appKey + "&app_secret=" + appSecret + "&grant_type=authorization_self";
        HttpRequestAll httpRequestAll = new HttpRequestAll();
        R result = httpRequestAll.doGet(url);

        System.out.println("返回结果：" + result);
        String message = result.getMessage();
        Map map = JSON.parseObject(message, Map.class);
        Object data = map.get("data");
        String dataStr = JSON.toJSONString(data);
        OauthVO oauthVO = JSON.parseObject(dataStr, OauthVO.class);
        String shop_id = oauthVO.getShop_id();
        stringRedisTemplate.boundValueOps(shop_id).set(dataStr);
        return oauthVO;
    }

    /***
     * 获取店铺的已授权品牌列表
     * @return
     */
    @Override
    public String getBrandList() throws UnsupportedEncodingException {
        Date date = new Date();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = dateFormat1.format(date);
        String format2 = dateFormat2.format(date);

        //有序 业务参数
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put(null, null);

        String shop_id = "173078";
        //通过redis获取access_token
        String oauth = stringRedisTemplate.boundValueOps(shop_id).get();
        OauthVO oauthVO = JSON.parseObject(oauth, OauthVO.class);
        String access_token = oauthVO.getAccess_token();
        String mapStr = JSON.toJSONString(linkedHashMap);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(linkedHashMap));
        String encode = URLEncoder.encode(jsonObject.toJSONString(), "UTF-8");

        String method = "methodshop.brandList";

        //拼接url
        String url = "https://openapi-fxg.jinritemai.com/shop/brandList?app_key=" + app_key + "&access_token=" + access_token + "&method=shop.brandList&param_json=" + encode + "&timestamp=" + format1 + "&v=2&sign=" + sign(app_key, mapStr, method, format2);

        Http http = new Http();
        String result = http.doGet(url);
        System.out.println(result);
        return result;
    }

    public String sign(String app_key, String mapStr, String method, String format2) {
        String secret = "8963b551-bd04-4be5-b02b-2e82ee0fccdb";
        String str = secret + "app_key" + app_key + method + "param_json" + mapStr + "timestamp" + format2 + "v2" + secret;
        String res = stringToMD5(str);
        return res;
    }


    public static String stringToMD5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有这个md5算法！");
        }
        StringBuilder md5code = new StringBuilder(new BigInteger(1, secretBytes).toString(16));
        while (md5code.length() < 32) {
            md5code.insert(0, "0");
        }
        return md5code.toString();
    }
}
